package main

import (
	"fmt"
	"github.com/go-test/protobuf/g"
	"google.golang.org/protobuf/proto"
	"io/ioutil"
	"os"
	"encoding/json"
)

func main() {
	//实例化模型对象，填充数据
	p := &g.Person{
		Id:    1,
		Name:  "jun",
		Books:   []string{"math", "english"},
	}

	//Marshal序列化
	out, err := proto.Marshal(p)
	if err != nil {
		panic(err)
	}
	//序列化得到结果是二进制的，是不可读的，所以这里保存到文件
	file, _ := os.OpenFile("out", os.O_CREATE|os.O_WRONLY, 0666)
	_, _ = file.Write(out)
	_ = file.Close()

	//unMarshal还原数据，从文件里面读取
	in, _ := os.Open("out")
	bytes, err := ioutil.ReadAll(in)
	if err != nil {
		panic(err)
	}
	p1 := &g.Person{}
	err = proto.Unmarshal(bytes, p1)
	if err != nil {
		panic(err)
	}
	//调用string()方法打印，也可以使用其生成的getter函数
	fmt.Printf("%s\n", p1.String())
	fmt.Printf("%d\n", p1.GetId())

	//json序列化
	out2, _ := json.Marshal(p)
	file2, _ := os.OpenFile("out2", os.O_CREATE|os.O_WRONLY, 0666)
	_, _ = file2.Write(out2)
	_ = file2.Close()
}